{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "# 获得 ip 地址\n",
    "ip_cmd = 'wsl ip a |wsl grep -w \"inet\" |wsl cut -d \" \" -f 6 |wsl cut -d \"/\" -f 1'\n",
    "shells = os.popen(ip_cmd).readlines()\n",
    "wsl_ip = shells[1].split(\"\\n\")[0]\n",
    "# 写入 Windows hosts 文件\n",
    "file_path = \"C:/Windows/System32/drivers/etc/hosts\"\n",
    "with open(file_path, \"r\") as f:\n",
    "    lines = f.readlines()\n",
    "\n",
    "found = False\n",
    "# 查找 hostname 为 ubuntu 的行\n",
    "for i, line in enumerate(lines):\n",
    "    if len(line) > 10 and line.find(\"ubuntu\") > -1:\n",
    "        found = True\n",
    "        # 替换为当前的 ip\n",
    "        lines[i] = wsl_ip + \"  ubuntu\"\n",
    "        break\n",
    "\n",
    "# 没有hostname 为 ubuntu 的行\n",
    "if not found:\n",
    "    lines.append(\"\\n\" + wsl_ip + \"  ubuntu\")\n",
    "\n",
    "# 写入文件\n",
    "if lines :\n",
    "    with open(file_path, \"w\") as f:\n",
    "        f.write(\"\".join(lines))"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
